package cn.chinasyq.photoquan;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * Created by 一搏 on 2015/12/19.
 *屏幕等宽ImageView
 */
public class MyImageView extends ImageView {
    public MyImageView(Context context) {
        super(context);
    }

    public MyImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public MyImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    public void setImageURI(Uri uri) {
        super.setImageURI(uri);
        final int oldWidth = getDrawable().getIntrinsicWidth();
        final int oldHeight = getDrawable().getIntrinsicHeight();
        getLayoutParams().width = getContext().getResources().getDisplayMetrics().widthPixels;
        getLayoutParams().height = (int) (getLayoutParams().width * (oldHeight / (oldWidth * 1f)));
        invalidate();
    }

    @Override
    public void setImageDrawable(Drawable drawable) {
        super.setImageDrawable(drawable);
        final int oldWidth = getDrawable().getIntrinsicWidth();
        final int oldHeight = getDrawable().getIntrinsicHeight();
        getLayoutParams().width = getContext().getResources().getDisplayMetrics().widthPixels;
        getLayoutParams().height = (int) (getLayoutParams().width * (oldHeight / (oldWidth * 1f)));
        invalidate();
    }

    @Override
    public void setImageBitmap(Bitmap bm) {
        super.setImageBitmap(bm);
        final int oldWidth = getDrawable().getIntrinsicWidth();
        final int oldHeight = getDrawable().getIntrinsicHeight();
        getLayoutParams().width = getContext().getResources().getDisplayMetrics().widthPixels;
        getLayoutParams().height = (int) (getLayoutParams().width * (oldHeight / (oldWidth * 1f)));
        invalidate();
    }

    @Override
    public void setImageResource(int resId) {
        super.setImageResource(resId);
        final int oldWidth = getDrawable().getIntrinsicWidth();
        final int oldHeight = getDrawable().getIntrinsicHeight();
        getLayoutParams().width = getContext().getResources().getDisplayMetrics().widthPixels;
        getLayoutParams().height = (int) (getLayoutParams().width * (oldHeight / (oldWidth * 1f)));
        invalidate();
    }
}
